package stack;

import java.util.Stack;

public class leetcode71简化路径 {
    public String simplifyPath(String path) {
        int length = path.length();
        int index = 0;
        Stack<String> stack = new Stack<>();
        while (index < length) {
            while (index < length && path.charAt(index) == '/') {
                index++;
            }
            if (index == length) {
                break;
            }
            StringBuilder str = new StringBuilder();
            while (index < length && path.charAt(index) != '/') {
                str.append(path.charAt(index));
                index++;
            }
            if (str.toString().equals(".")) {

            } else if (str.toString().equals("..")) {
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            } else {
                stack.push(str.toString());
            }
        }
        int size = stack.size();
        if (size == 0) {
            return "/";
        }
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < size; i++) {
            str.insert(0, stack.pop());
            str.insert(0, "/");
        }
        return str.toString();
    }
}
